package com.tangerine.bd;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

public class DbHandler {
	
	private SQLiteDatabase bd;
	private static DbHandler BdManejador;
	private static Context myContext;

	public DbHandler(String pathBD) {
		bd = SQLiteDatabase.openDatabase(pathBD, null, 0);
	}
	
	public static DbHandler getInstance() {
		return BdManejador;
	}
	
	public static void initInstance(String pathBD, Context context) {
		myContext = context;
		
		if(BdManejador == null)
		{
			File DirectorioSonarApp = new File(Environment.getExternalStorageDirectory() + "/Sonar");
			if(!(DirectorioSonarApp.exists() && DirectorioSonarApp.isDirectory()))
			{
				DirectorioSonarApp.mkdirs();
			}
			File ArchivoBD = new File(Environment.getExternalStorageDirectory() + "/Sonar/SonarApp_BD.sqlite");
			if(ArchivoBD.exists())
			{
				BdManejador = new DbHandler(pathBD);
			}
			else
			{
				String nameBD = "SonarApp_BD.sqlite";
				try {
					copyDataBase(nameBD, pathBD);
					BdManejador = new DbHandler(pathBD);
				} 
				catch(IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	private static void copyDataBase(String nameBD, String pathBD) throws IOException {
		//Open your local db as the input stream
		InputStream InPut = myContext.getAssets().open(nameBD);

		// Path to the just created empty db
		String outFileName = pathBD;

		//Open the empty db as the output stream
		OutputStream OutPut = new FileOutputStream(outFileName);

		//transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		
		while((length = InPut.read(buffer)) > 0) {
			OutPut.write(buffer, 0, length);
		}

		//Close the streams
		OutPut.flush();
		OutPut.close();
		InPut.close();
	}

	public Cursor ejecutarConsulta(String selectQuery){
		
		Cursor cursor = bd.rawQuery(selectQuery, null);
		
		return cursor;
	}
	
	public void ejecutarInsert(String insertQuery){
		
		bd.execSQL(insertQuery);
	}
	
	public void ejecutarDelete(String deleteQuery){	
		
		bd.execSQL(deleteQuery);
	}
}

